<template>
	<view class="page-ai-image-make page-common">
		<scroll-view :style="{
			height: `calc(100vh - 550rpx)`,
		}" scroll-y="true">
			<view class="top-contianer">
				<view class="flex-center">
					<view class="">
						<view v-if="photoUrl" class="photo-image">
							<image :src="photoUrl" mode="aspectFit"></image>
						</view>
						<template v-else>
							<view class="upload-box" @tap="onChoosePhoto">
								<text class="add-icon">+</text>
								<view class="add-text">点击上传你的照片</view>
							</view>
						</template>
						<view class="text-center font-12 mt-8">
							当前照片
						</view>
					</view>
					<view class="">
						<view class="photo-image ml-16">
							<image :src="templateUrl" mode="aspectFit"></image>
						</view>
						<view class="text-center font-12 mt-8">
							生成风格
						</view>
					</view>

				</view>
				<view v-if="!uploadStatus">
					<view class="text-center font-16 bold mt-16">请上传一张你的半身或全身照</view>
					<view class="text-center font-12 grey mt-8">上传照片需要符合规范，不能穿自带帽子的服装等，否则会影响最终生成效果</view>
				</view>

				<view v-else-if="uploadStatus === 'error'">
					<view class="text-center font-16 bold mt-16 red">检测不合格</view>
					<view class="text-center font-12 grey mt-8">失败原因：{{failedReason}}</view>
				</view>

				<view v-else-if="uploadStatus === 'success'">
					<view class="text-center font-16 bold mt-16 green">上传成功</view>
					<view class="text-center font-12 grey mt-8">点击立即生成即可生成AI形象照</view>
				</view>

				<view v-if="uploadStatus" class="reupload-button custom-button white-btn-gray-text mt-8"
					@tap="onChoosePhoto">
					<u-button type="primary" shape="circle" text="重新上传"></u-button>
				</view>
			</view>

		</scroll-view>

		<view class="field-container">
			<view class="flex-start-center">
				<image class="photo-icon" src="/static/other/photo-suggestions.png" mode="aspectFit"></image>
				<text class=" font-16 bold ml-8">拍摄规范</text>
			</view>
			<view class="g-box mt-16 flex-center">
				<view :class="{
					'ml-9': index > 0,
				}" v-for="(item, index) in gList" :key="item.img">
					<image class="g-img" :src="item.img" mode="aspectFit"></image>
					<view class="text-center font-12 mt-8">{{item.text}}</view>
				</view>
			</view>
			<view class="btn-double">
				<view class="custom-button full-button mt-16 preview-btn">
					<u-button @click="onPreview" type="primary" plain shape="circle" text="预览效果"></u-button>
				</view>
				<view class="custom-button full-button mt-16">
					<u-button @click="onSubmit" :disabled="uploadStatus !== 'success'" type="primary" shape="circle"
						:text="freeNum > 0 ? '立即生成' : `支付 ${discount / 100}元 生成`"></u-button>
				</view>
			</view>

			<u-safe-bottom></u-safe-bottom>
		</view>
		<u-popup :show="showPreviewModal" :round="16" mode="center" :safeAreaInsetBottom="false">
			<view class="preview-container">
				<view class="normal-title-16 flex-start-center bold">
					<text class="flex-1 text-center">预览效果</text>
				</view>
				<view class="mt-16 flex-center">
					<view class="">
						<view class="photo-image">
							<image :src="modelFigureImage" mode="aspectFit"></image>
						</view>
						<view class="text-center font-12 mt-8">
							原图
						</view>
					</view>
					<view class="">
						<view class="photo-image ml-16">
							<image :src="modelEffectImage" mode="aspectFit"></image>
						</view>
						<view class="text-center font-12 mt-8">
							生成效果
						</view>
					</view>
				</view>
				<view class="mt-16 desc text-center">
					实际生成效果取决于上传照片的质量
				</view>
				<view class="btn-double mt-16">
					<view class="custom-button full-button" @tap="showPreviewModal = false">
						<u-button type="primary" shape="circle">
							我知道了
						</u-button>
					</view>
				</view>

			</view>

		</u-popup>
		<view style="visibility: hidden;position: fixed; top: 200vh">
			<image :src="tempImage" @load="onImageLoad"></image>
		</view>
	</view>


</template>

<script setup>
	import {
		ref,
		reactive
	} from "vue";
	import {
		onLoad,
	} from '@dcloudio/uni-app';
	import {
		uploadFile
	} from '@/common/js/method';
	import {
		getPaymentType,
	} from '@/common/js/method.js';
	import {
		payType,
	} from '@/common/js/data.js';;

	const freeNum = ref(0); //首次免费
	// const isValid = ref(false); //图片校验通过
	const discount = ref(''); // 折扣价，单位：分
	const uploadStatus = ref(''); // 图片上传状态
	const failedReason = ref(''); // 图片校验失败原因
	const tempImage = ref('');
	const photoUrl = ref(''); //
	const templateId = ref('');
	const templateUrl = ref('');
	const modelFigureImage = ref(''); //示例原图
	const modelEffectImage = ref(''); //示例效果图
	const gList = ref([{
			img: '/static/ai/g-1.png',
			text: '五官清晰',
		},
		{
			img: '/static/ai/g-2.png',
			text: '不是正面',
		}, {
			img: '/static/ai/g-3.png',
			text: '光线不佳',
		}, {
			img: '/static/ai/g-4.png',
			text: '面部遮挡',
		}, {
			img: '/static/ai/g-5.png',
			text: '佩戴眼镜',
		}
	]);

	const resetImageCache = () => {}

	const onChoosePhoto = () => {
		uni.chooseImage({
			count: 1, //默认9
			sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
			// sourceType: ['album'], //从相册选择
			success: function(res) {
				// image加载tempImage并读取宽高，进行校验后再上传 => onImageLoad
				// resetImageCache();
				console.log('chooseImage', res)
				// 校验图片文件大小
				const fileSizeKB = res.tempFiles[0].size / 1024; //KB
				if (fileSizeKB < 5 || fileSizeKB > 5 * 1024) {
					uni.$u.toast('图片大小应在5KB~5MB之间');
					return;
				}
				tempImage.value = res.tempFilePaths[0];
			}
		});
	};

	const checkImg = async (imgUrl) => {
		try {
			return await uni.$request('/api/busi/image/class/check', {
				image: imgUrl
			})

		} catch (e) {
			uni.$u.toast('图片校验接口失败');
		}

	}

	// 制作形象照(预下单， 后端在支付回调制作)
	const makeImgPhoto = async () => {
		const paymentType = await getPaymentType();
		const _payType = payType[paymentType];
		const res = await uni.$request('/api/busi/image/model/make', {
			image: photoUrl.value,
			id: templateId.value,
			payType: _payType,
		});
		console.log('制作形象照', res)
		// 如果需要支付
		if (res.data) {
			await uni.$pay(res.data);
		}
	}

	const onImageLoad = async (e) => {
		console.log('onImageLoad', e)
		if (+e.detail.width > 4096 || +e.detail.height > 4096) {
			uni.$u.toast('图片宽/高过大，不能超过4096px')
			return;
		}
		if (+e.detail.width < 150 || +e.detail.height < 150) {
			uni.$u.toast('图片宽/高过小，不能低于150px')
			return;
		}
		uni.showLoading({
			title: '上传中'
		});
		photoUrl.value = await uploadFile(tempImage.value);
		const checkRes = await checkImg(photoUrl.value);
		if (checkRes.status === 200) {
			uploadStatus.value = 'success';
		} else {
			uploadStatus.value = 'error';
			failedReason.value = checkRes.message;
		}
		uni.hideLoading();
	}
	const showPreviewModal = ref(false);
	const onPreview = async () => {
		showPreviewModal.value = true;
	}
	const onSubmit = async () => {
		await makeImgPhoto();
		uni.redirectTo({
			url: '/sub-ai/pages/ai-image/res'
		})
	}
	onLoad(() => {
		const itemData = uni.getStorageSync('ai-make-item');
		console.log('ai-make-item', itemData)
		templateUrl.value = itemData.modelImage;
		modelFigureImage.value = itemData.modelFigureImage;
		modelEffectImage.value = itemData.modelEffectImage;
		discount.value = itemData.discount;
		templateId.value = itemData.id;
		freeNum.value = itemData.freeNum;
	})
</script>

<style lang="scss" scoped>
	.page-ai-image-make {
		padding: 0 32rpx 0 32rpx;

		.top-contianer {
			padding-top: 80rpx;
			padding-bottom: 32rpx;
		}

		.upload-box {
			box-sizing: border-box;
			width: 300rpx;
			height: 400rpx;
			background: rgba(255, 255, 255, 1);
			box-shadow: 0px 4rpx 8rpx rgba(0, 0, 0, 0.02);
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;

			.add-icon {
				font-size: 56rpx;
				color: rgba(166, 166, 166, 1);
				margin-bottom: 6rpx;
			}

			.add-text {
				// margin-top: 4px;
				font-size: 24rpx;
				line-height: 40rpx;
				color: rgba(166, 166, 166, 1);
			}
		}

		.photo-image {
			width: 300rpx;
			height: 400rpx;

			image {
				width: 100%;
				height: 100%;
			}
		}

		.field-container {
			width: 100%;
			box-sizing: border-box;
			border-radius: 32rpx 32rpx 0 0;
			background: rgba(255, 255, 255, 1);
			box-shadow: 0px -4rpx 12rpx rgba(0, 0, 0, 0.02);
			padding: 32rpx;
			position: fixed;
			left: 0;
			bottom: 0;
			z-index: 9999;
			// height: 550rpx;
			display: flex;
			flex-direction: column;
			justify-content: space-between;

			.photo-icon {
				width: 24px;
				height: 24px;
			}

			.g-box {
				border-radius: 8px;
				background: rgba(245, 245, 245, 1);
				padding: 24rpx 32rpx;

				.g-img {
					width: 110rpx;
					height: 154rpx;
				}
			}
		}
		.preview-btn {
			width: 240rpx;
			flex: none;
		}
		.preview-container {
			padding: 32rpx;
		}
	}
</style>